//
//  RecommendViewController.m
//  CommonFrame
//
//  Created by Bang-guo on 15/7/15.
//  Copyright (c) 2015年 guobang. All rights reserved.
//

#import "RecommendViewController.h"
#import "RecommendTalbleCell.h"
#import "RecommendScroll.h"


@interface RecommendViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *recommendTableView;




@end

@implementation RecommendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"推荐";

    self.intNum = 0;
    self.nextPage = 1;
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.scrollArray = [NSMutableArray array];
    self.allArray = [NSMutableArray array];
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位未开");
    }
    else {
        NSLog(@"开启定位");
    }

    [self getLoaction];
    
    self.recommendTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 20 - 44 - 49) style:UITableViewStylePlain];
    self.recommendTableView.delegate = self;
    self.recommendTableView.dataSource = self;
    [self.view addSubview:self.recommendTableView];
    
    self.recommendScroll = [[RecommendScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200)];
    self.recommendScroll.myDelegate = self;
    self.recommendTableView.tableHeaderView = self.recommendScroll;
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载中...";
    [self.HUD show:YES];
    //下来刷新  上拉加载
//    [self.recommendTableView.header beginRefreshing];
    [self headerRefesh];
    [self footerRefesh];
    
    
}

-(void)headerRefesh {
    self.recommendTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.nextPage = 1;

        //让菊花旋转起来
        self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.HUD.labelText = @"正在加载中...";
        [self.HUD show:YES];
        [self getDataValue];

    }];
    
}

-(void)footerRefesh {
    
    self.recommendTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        self.nextPage = self.recNext.nextPage;
//        self.downUpdata = NO;
        self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.HUD.labelText = @"正在加载中...";
        [self.HUD show:YES];
        [self getDataValue];

    }];
    
}
-(void)sendMessage:(NSInteger)intNum {
    
    RecommendScroll *rec = self.scrollArray[intNum];
    if ([rec.type isEqualToString:@"4"]) {
        
        RecommendDetailViewController *recommendD = [[RecommendDetailViewController alloc] init];
        recommendD.recommendScroll = rec;
        
        
        [self.navigationController pushViewController:recommendD animated:YES];
        
    }
    
    
}

-(void)getDataValue {
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *str_url = @"";
    if (self.nextPage == 1) {
        
        NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/?lat=%@&lng=%@", [userDefaults objectForKey:@"latitude"], [userDefaults objectForKey:@"longitude"]];
        str_url = str;
        self.allArray = [NSMutableArray array];
    } else {
        
        NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/?next_start=%@", [NSString stringWithFormat:@"%ld", self.nextPage]];
        str_url = str;
        NSLog(@"1111  =  %@", str_url);
    }
    
   [AFNGetDataValue getDataAFN:str_url block:^(NSMutableDictionary *dataDic) {
       self.recNext = [[RecommendScroll alloc] init];
       self.recNext.nextPage = [[NSString stringWithFormat:@"%@", [dataDic objectForKey:@"next_start"]] integerValue];

       NSMutableArray *array = [NSMutableArray arrayWithArray:[dataDic objectForKey:@"elements"]];
//       NSMutableDictionary *dic = [array firstObject];
//       NSMutableArray *dataArray = [dic objectForKey:@"data"];
//       NSMutableArray *firstArray = [dataArray firstObject];
//       for (NSMutableDictionary *tempDic in firstArray) {
//           
//           RecommendScroll *rec = [[RecommendScroll alloc] init];
//           [rec setValuesForKeysWithDictionary:tempDic];
//           [self.scrollArray addObject:rec];
//           
//       }
       int i = 0;
       for (NSMutableDictionary *dic in array) {
           
           RecommendScroll *rec = [[RecommendScroll alloc] init];

           rec.type = [NSString stringWithFormat:@"%@", [dic objectForKey:@"type"]];
           NSMutableArray *dataArray = [dic objectForKey:@"data"];
           NSMutableDictionary *dic1 = [dataArray firstObject];
           if (self.nextPage == 1) {
               
               if (i >= 7) {
                   
                   [rec setValuesForKeysWithDictionary:dic1];
                   rec.uId = [NSString stringWithFormat:@"%@", [dic1 objectForKey:@"id"]];
                   NSMutableDictionary *userDic = [dic1 objectForKey:@"user"];
                   rec.userName = [userDic objectForKey:@"name"];
                   rec.avatar_m = [userDic objectForKey:@"avatar_m"];
                   
               }
               
           } else {
               [rec setValuesForKeysWithDictionary:dic1];
               rec.uId = [NSString stringWithFormat:@"%@", [dic1 objectForKey:@"id"]];
               NSMutableDictionary *userDic = [dic1 objectForKey:@"user"];
               rec.userName = [userDic objectForKey:@"name"];
               rec.avatar_m = [userDic objectForKey:@"avatar_m"];
           }
           
           [self.allArray addObject:rec];
           i++;
       }
       if (self.nextPage == 1) {
           
           for (int i = 0; i < 7; i++) {
               if (self.allArray.count > 7) {
                   
                   [self.allArray removeObjectAtIndex:0];
                   
               }
               
           }
           
       }

       for (int i = 0; i < self.allArray.count; i++) {
           
           RecommendScroll *rec = self.allArray[i];
           if (!([rec.type isEqualToString:@"4"] || [rec.type isEqualToString:@"5"])) {
               
               [self.allArray removeObjectAtIndex:i];
               
           }
           
           
           
       }
       
//       NSLog(@"self.allArray.count %ld", self.allArray.count);
       if (self.nextPage == 1) {
           self.scrollArray = [NSMutableArray arrayWithArray:self.allArray];
           for (int i = 0; i < self.scrollArray.count; i++) {
               RecommendScroll *rec = self.scrollArray[i];
               if (![rec.type isEqualToString:@"4"]) {
                   
                   
                   [self.scrollArray removeObjectAtIndex:i];
                   
               }
               
           }
           
           if (self.scrollArray.count != 0) {
               
               [self.recommendScroll setImages:self.scrollArray];
               
               
           }
       }
       [self.recommendTableView reloadData];
       // 拿到当前的下拉刷新控件，结束刷新状态
       [self.recommendTableView.footer endRefreshing];
       [self.recommendTableView.header endRefreshing];
       [self.HUD hide:YES];
       NSLog(@"%ld", self.allArray.count);
   }];
               
               

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    RecommendScroll *rec = self.allArray[indexPath.row];
    if ([rec.type isEqualToString:@"4"]) {
        
        RecommendDetailViewController *recommendD = [[RecommendDetailViewController alloc] init];
        recommendD.recommendScroll = self.allArray[indexPath.row];
        
        
        [self.navigationController pushViewController:recommendD animated:YES];
        
    }
    
    if ([rec.type isEqualToString:@"5"]) {
        
        
        WebViewController *web = [[WebViewController alloc] init];
        web.recommendScroll = self.allArray[indexPath.row];
        
        [self.navigationController pushViewController:web animated:YES];
        
    }
//    rec.type  还有 6  和  7
    
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.allArray.count;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"cell";
//    NSString *identifier = [NSString stringWithFormat:@"cell%ld", indexPath.row];
//    RecommendTalbleCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    RecommendTalbleCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        
        cell = [[RecommendTalbleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }

//    if (!cell) {
//        cell = [[RecommendTalbleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
//    }
//    else//当页面拉动的时候 当cell存在并且最后一个存在 把它进行删除就出来一个独特的cell我们在进行数据配置即可避免
//    {
//        while ([cell.contentView.subviews lastObject] != nil) {
//            [(UIView *)[cell.contentView.subviews lastObject] removeFromSuperview];
//        }
//    }
    RecommendScroll *recommend = [[RecommendScroll alloc] init];
    if (self.allArray.count != 0) {
        
        recommend = self.allArray[indexPath.row];
        
    }
    cell.recommmendScroll = recommend;
//    cell.textLabel.text = @"1";
    
    return cell;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 220.0;
}

-(void)getLoaction{

    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.distanceFilter = 1;
    self.locationManager.desiredAccuracy = kCLDistanceFilterNone;
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
        
        [_locationManager requestWhenInUseAuthorization];
        
    }
    [self.locationManager startUpdatingLocation];
    
}
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations{

    if (self.intNum == 1) {
        
        return;
    }
    CLLocation *currLocation = [locations lastObject];
    
    NSString *latitude = [NSString stringWithFormat:@"%f", currLocation.coordinate.latitude];
    NSString *longitude = [NSString stringWithFormat:@"%f", currLocation.coordinate.longitude];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //纬度
    [userDefaults setValue:latitude forKey:@"latitude"];
    //经度
    [userDefaults setValue:longitude forKey:@"longitude"];
    
    NSLog(@"纬度 = %@ 经度 = %@", latitude, longitude);
    [self getDataValue];
    self.intNum = 1;
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
